package com.fh.servlet.annotation;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

/**
 * @author 方小勤
 * @version 1.0~
 * 模拟一把 Tomcat 时如何通过 @WebServlet(urlPatterns = {"/ok1", "/ok2"}) 来装载一个 Servlet
 */
public class TestAnnotationServlet {
    private static final HashMap<String,Object> map = new HashMap<>();
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //1. 首先要得到扫描的包 路径 io，进而得到类的全路径
        String classAllPath = "com.fh.servlet.annotation.OKServlet";
        //2. 得到 OkServlet 的Class对象
        Class<?> aClass = Class.forName(classAllPath);
        //3. 通过class对象，得到Annotation
        WebServlet annotation = aClass.getAnnotation(WebServlet.class);
        System.out.println(annotation);
        String[] urls = annotation.urlPatterns();
        for (String url : urls) {
            System.out.println("url = " + url);
        }
        //如果匹配 url，如果时第一次，Tomcat 就会创建一个OkServlet实例，放入到HashMap中
        Object object = aClass.getConstructor().newInstance();
        System.out.println(object);
        //简单的模拟
        map.put(annotation.name(), object);
        System.out.println(object);
    }
}
